package com.cavy.platform.server;

import lombok.Data;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.List;

/**
 * 错误返回值
 */
@Data
public class ErrorResult extends ResultInfo {

    public ErrorResult(Exception e) {
        super(null);
        this.setSuccess(false);
        if (e instanceof BindingErrorException) {
            BindingErrorException errorException = (BindingErrorException) e;
            buildErrorItem(errorException.getErrorList());
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            List<ObjectError> allErrors = bindException.getAllErrors();
            buildErrorItem(allErrors);
        } else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            buildErrorItem(exception.getBindingResult().getAllErrors());
        } else {
            this.getErrors().add(new ErrorItem(e.getMessage()));
        }
    }

    private void buildErrorItem(List<ObjectError> errorList) {
        List<ErrorItem> errors = getErrors();
        for (ObjectError error : errorList) {
            errors.add(convertItem(error));
        }
    }

    private ErrorItem convertItem(ObjectError error) {
        return new ErrorItem(error);
    }


}
